import axios from 'axios'
export default {
  state () {
    return {
      list: []
    }
  },
  mutations: {
    changeList (state, list) {
      state.list = list
    },
    // addList (state, obj) {
    //   const obj1 = state.list.find(item => item.id == obj.id)
    //   obj1.count = obj.count
    // }

  },
  actions: {
    async getList ({ commit }) {
      const res = await axios('http://localhost:3000/cart')
      commit('changeList', res.data)
    },
    async syncCount ({ commit }, obj) {
      // const res = await axios.patch('http://localhost:3000/cart/' + obj.id, {
      //   count: obj.count
      // })
      // console.log(obj.id, res)
      // commit('addList', obj)

      return new Promise(async (resolve, reject) => {
        const res = await axios.patch('http://localhost:3000/cart/' + obj.id, {
          count: obj.count
        })
        resolve(res)
      })
    }
  },
  getters: {
    total (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },
    totalPrice (state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)

    },
  },
  namespaced: true
}